package com.yx.filesystem.storage;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.math.BigInteger;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
public class StateHandler extends SocketHandler {
	
	public StateHandler() {
		// TODO 自动生成的构造函数存根
	}

	@Override
	public boolean handler(BufferedInputStream socketInput,
			BufferedOutputStream socketOutput, Transport transport)
			throws Exception {
		JSONObject requestContent = transport.getJsonContent();
		String nodeId = requestContent.getString("NODE_ID");
		Hashtable<String, BigInteger> storageSaveState = Server.get()
				.getStorageSaveState();
		JSONObject returnContent = new JSONObject();
		JSONObject nodeState = new JSONObject();
		if ("ALL_STATE".equals(nodeId)) {
			Enumeration<String> list = storageSaveState.keys();
			while (list.hasMoreElements()) {
				String key = list.nextElement();
				String value = storageSaveState.get(key).toString();
				nodeState.put(key, value);
			}
		} else {
			if (storageSaveState.containsKey(nodeId)) {
				String value = storageSaveState.get(nodeId).toString();
				nodeState.put(nodeId, value);
			}			
		}
		returnContent.put("NODE_STATE", nodeState);
		returnContent.put("NODE_ID", Server.get().getServerNode().getId());
		JSONArray backupArray=new JSONArray();
		List<Node> backNodes=Server.get().getServerNode().getBachupNodes();
		for(Node bNode:backNodes){
			backupArray.put(bNode.getId()+"("+bNode.getHost()+":"+bNode.getPort()+")");
		}
		returnContent.put("BACKUP_NODE", backupArray);
		returnContent.put("NODE_TOTALSPACE", SpaceChecker.getTotalSpace());
		returnContent.put("NODE_USEDSPACE", SpaceChecker.getUsedSpace());
		returnContent.put("NODE_FREESPACE", SpaceChecker.getFreeSpace());
		returnContent.put("NODE_SPACE_FULL", SpaceChecker.isSpaceFull());
		
		Transport returnTransport = new Transport("", true, "成功", returnContent);
		returnTransport.write(socketOutput);
		return true;
	}

}
